﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
using A2DFramework.EventService.Configuration;
using A2DFramework.EventService.Providers;
using System.Threading;

namespace A2DFramework.EventService.Factory
{
    public static class RedisFactory
    {
        private static RedisClient redisClient_Publish = null;
        private static object lockObj_Publish = new object();

        private static RedisClient redisClient_Subscribe = null;
        private static object lockObj_Subscribe = new object();


        private static List<RedisSubscribeReceiver> RedisSubscribeReceivers = new List<RedisSubscribeReceiver>();
        private static object lockObj_RedisSubscribeReceivers = new object();

        public static RedisClient GetRedisClient_Publishable()
        {
            lock (lockObj_Publish)
            {
                if (redisClient_Publish == null)
                    redisClient_Publish = new RedisClient(EventServiceConfiguration.RedisSettings.ReadWriteServerIps.First());

                return redisClient_Publish;
            }
        }

        public static RedisClient GetRedisClient_Subscribe()
        {
            lock (lockObj_Subscribe)
            {
                if (redisClient_Subscribe == null)
                    redisClient_Subscribe = new RedisClient(EventServiceConfiguration.RedisSettings.ReadWriteServerIps.First());

                return redisClient_Subscribe;
            }
        }

        public static void TouchReceiveThread()
        {
            if (RedisSubscribeReceivers != null && RedisSubscribeReceivers.Count > 0)
                return;

            lock (lockObj_RedisSubscribeReceivers)
            {
                if (RedisSubscribeReceivers != null && RedisSubscribeReceivers.Count > 0)
                    return;

                //开启接收消息线程
                RedisSubscribeReceiver rsr = new RedisSubscribeReceiver(GetRedisClient_Subscribe(), Starter.eventResolver.Resolve);
                ThreadPool.QueueUserWorkItem(new WaitCallback(rsr.Start));
                Thread.Sleep(200);

                //将线程加入线程池
                RedisSubscribeReceivers.Add(rsr);
            }
        }
    }
}